package com.snj.visangedu;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.news.NewsAdapter3;
import com.snj.visangedu.news.NewsItem2;
import com.snj.visangedu.news.NewsItem3;

public class SecretPlannerFragment extends Fragment implements OnClickListener {
	private final String TAG = "SecretPlannerFragment";
		
	ListView lstv_menu2 = null;
	NewsAdapter3 _adapter = null;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View root = inflater.inflate(R.layout.fragment_secretplanner,
				container, false);
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d(TAG, "onActivityCreated");
		
		super.onActivityCreated(savedInstanceState);
		init_widget();
	}
	
	private void init_widget() {
		View view = getView();

		
		lstv_menu2 = (ListView)view.findViewById(R.id.lstv_secretplanner);
		
		
		_adapter = new NewsAdapter3(getActivity(), R.layout.list_news, Global.mNews3);
		lstv_menu2.setAdapter(_adapter);
		_adapter.notifyDataSetChanged();
		
		
		
		
		new AsyncTask<String, String, String>() {
			
			ArrayList<NewsItem3> tempnews = new ArrayList<NewsItem3>();

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				String result = "";
            	JSONObject resultobj = null;
            	String imgsrc = "", coversrc = "";
            	Bitmap img = null, coverimg = null;
            	String id = "";
            	
            	
            	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				
            	while(true)
            	{
					postParameters.clear();
					postParameters.add(new BasicNameValuePair("begin", String.format("%d", Global.loadedimgcount2)));
					postParameters.add(new BasicNameValuePair("count", String.format("%d", Global.loadingimgcount)));
					
					Log.d(TAG, postParameters.toString());
					
					try {
						result = CustomHttpClient.executeHttpPost(Global.newsurl3, postParameters);							
						resultobj = new JSONObject(result);
						
						Log.d(TAG, result);
						
						tempnews.clear();
						
						try
						{
							JSONObject obj = new JSONObject(result);
							JSONArray arr = obj.getJSONArray("data");
							
							if(arr.length() == 0)	// ������ �� �ҷ�����
							{
								return "complete";
							}
							
							Global.totalloadedimgcount2 += arr.length();
							
							String filename_img = "";
							String fullpath_img = "";
							
							for(int i=0; i<arr.length(); i++)
							{
								Log.d(TAG, arr.getJSONObject(i).getString("imgsrc"));
								
								filename_img = arr.getJSONObject(i).getString("imgsrc").replace(".jpg", ".venews") + arr.getJSONObject(i).getString("updatever");
								fullpath_img = "/visang/news3/" + filename_img;
								
								Log.d(TAG, "���翩��1 : " + Global.FileExist(fullpath_img, "") + ", " + Global.ex_storage + "/" + filename_img);
								
								
								if(!Global.FileExist(fullpath_img, ""))
								{
									img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "newsimages3/" + arr.getJSONObject(i).getString("imgsrc"));
									Global.saveBitmaptoJpeg(img, "/visang/news3", filename_img);
								}
								else
								{
									img = BitmapFactory.decodeFile(Global.ex_storage + fullpath_img);
								}
								
								id = arr.getJSONObject(i).getString("id");
								imgsrc = Global.vnpbaseurl + "newsimages3/" + arr.getJSONObject(i).getString("imgsrc");
								coversrc = Global.vnpbaseurl + "contents/" + arr.getJSONObject(i).getString("id") + "/" + arr.getJSONObject(i).getString("cover"); 
								
								
								//img = CustomHttpClient.downloadBitmap(imgsrc);
								//coverimg = CustomHttpClient.downloadBitmap(coversrc);
								coverimg = null;
								tempnews.add(new NewsItem3(arr.getJSONObject(i).getString("no"), arr.getJSONObject(i).getString("title"), arr.getJSONObject(i).getString("content"), Global.baseurl + "newsimages/" + arr.getJSONObject(i).getString("imgsrc"), img, coverimg));
								
								//Global.mNews.add(new NewsItem("", "", "", Global.baseurl + "newsimages/" + arr.getJSONObject(i).getString("imgsrc"), img, arr.getJSONObject(i).getString("link")));
							}
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
						
						
					}
					catch (JSONException e)
					{					
						e.printStackTrace();
					}
					catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();					
						
					}
					
					while(Global.loadedimgcount < Global.totalloadedimgcount)
					{
						try {
							Thread.sleep(1);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
					publishProgress("");
            	}
				
				//return null;
			}
			
			

			@Override
			protected void onProgressUpdate(String... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
				
				Log.d(TAG, "Update");
				Global.mNews3.addAll(tempnews);
				_adapter.SetList(Global.mNews3);
				_adapter.notifyDataSetChanged();
			}



			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
								
				Log.d(TAG, "Complete");
				_adapter.SetList(Global.mNews3);
				_adapter.notifyDataSetChanged();
				
				
			}
		}.execute("");
		
		
		lstv_menu2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				//Log.d(tag, "link : " + Global.mNews.get(position).GetLink());
				_adapter.SetList(Global.mNews3);
				_adapter.notifyDataSetChanged();
				
				
				Log.d(TAG, "ContentActivity3");
				Intent contentintent = new Intent(getActivity(), ContentActivity3.class);
				
				
				
				if(position > 0)
				{
					contentintent.putExtra("prev", Global.mNews3.get(position-1).GetNo());
				}
				
				contentintent.putExtra("no", Global.mNews3.get(position).GetNo());
				contentintent.putExtra("position", position);
				contentintent.putExtra("type", "2");
				
				
				if(position < (Global.mNews3.size() - 1))
				{
					contentintent.putExtra("next", Global.mNews3.get(position+1).GetNo());
				}
				startActivity(contentintent);
			}
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		
		switch(v.getId())
		{
		case R.id.img_menu2_submenu1:
			break;
		case R.id.img_menu2_submenu2:
			break;
		}
	}
	
	
}
